﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Dimebrain.TweetSharp.Extensions;
using Dimebrain.TweetSharp.Fluent;
using Newtonsoft.Json;

namespace AreYouFollowingMe.Controllers
{
    [HandleError]
    public class HomeController : baseController
    {
        private int PAGEINTERVAL = 10;
        public ActionResult Index()
        {
            // check if access token and tokenSecret exists
            if (Request.Cookies["auth_token"] == null ||
                Request.Cookies["auth_secret"] == null)
            {
                return View("Welcome");
            }
            return View();
        }

        private object[] GetNoFollowMeResults(string screenName, bool more)
        {
            HashSet<string> names = new HashSet<string>();
            int page = 0;
            long? cursor = -1;
            bool finito = false;
            try
            {
                var token = HttpUtility.UrlDecode(Request.Cookies["auth_token"].Value);
                var secret = HttpUtility.UrlDecode(Request.Cookies["auth_secret"].Value);

                var follower = FluentTwitter.CreateRequest()
                    .Configuration.UseGzipCompression()
                    .AuthenticateWith(_consumerKey,
                                      _consumerSecret,
                                      token,
                                      secret)
                    .SocialGraph()
                    .Ids()
                    .ForFollowers()
                    .AsJson().Request();

                var ids = follower.As<List<int>>();
                
                HashSet<int> followerSet = new HashSet<int>();
                foreach (var entry in ids)
                {
                    followerSet.Add(entry);
                }

                bool moreTodo = true;
                
                if (more)
                {
                    page = (int)Session["page"];
                }
                else
                {
                    Session["page"] = 0;
                }
                
                while (moreTodo)
                {
                    // get following
                    var twitter = FluentTwitter.CreateRequest()
                            .Configuration.UseGzipCompression()
                            .AuthenticateWith(_consumerKey,
                                                  _consumerSecret,
                                                  token,
                                                  secret)
                            .Users()
                            .GetFriends()
                            .GetCursor(cursor.Value)
                            .AsJson();
                    var response = twitter.Request();
                    var friends = response.AsUsers();
                    cursor = response.AsNextCursor();
                    page++;
                    if (!cursor.HasValue ||
                        cursor.Value == 0 )
                    {
                        if (page % PAGEINTERVAL != 0)
                        {
                            finito = true;
                        }
                        Session["page"] = page;
                        moreTodo = false;
                    }

                    // delete followers from following
                    foreach (var user in friends)
                    {
                        if (!followerSet.Contains(user.Id))
                        {
                            var imgLink = "<img class='pi' align='absmiddle' src='" + user.ProfileImageUrl + "' />&nbsp;";
                            names.Add("<a href='http://twitter.com/" + user.ScreenName + "' target='_blank'>" + imgLink + user.ScreenName + "</a>");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Session["page"] = page;
                names.Add(ex.Message);
            }
            object[] data = new object[2];
            data[0] = names;
            data[1] = finito;
            return data;
        }

        public ActionResult GetList1(string id)
        {
            
            return Json(GetNoFollowMeResults(id, false));
        }

        public ActionResult MoreList1(string id)
        {

            return Json(GetNoFollowMeResults(id, true));
        }

        public object[] GetMeNoFollowResults(string screenName, bool more)
        {
            HashSet<string> names = new HashSet<string>();
            int page = 0;
            long? cursor = -1;
            bool finito = false;
            try
            {
                var token = HttpUtility.UrlDecode(Request.Cookies["auth_token"].Value);
                var secret = HttpUtility.UrlDecode(Request.Cookies["auth_secret"].Value);

                var friends = FluentTwitter.CreateRequest()
                    .Configuration.UseGzipCompression()
                    .AuthenticateWith(_consumerKey,
                                      _consumerSecret,
                                      token,
                                      secret)
                    .SocialGraph()
                    .Ids()
                    .ForFriends()
                    .AsJson()
                    .Request();
                
                var ids = friends.As<List<int>>();

                HashSet<int> friendSet = new HashSet<int>();
                foreach (var entry in ids)
                {
                    friendSet.Add(entry);
                }

                bool moreTodo = true;

                if (more)
                {
                    page = (int)Session["page"];
                }
                else
                {
                    Session["page"] = 0;
                }

                while (moreTodo)
                {
                    // get follower
                    var twitter = FluentTwitter.CreateRequest()
                            .Configuration.UseGzipCompression()
                            .AuthenticateWith(_consumerKey,
                                                  _consumerSecret,
                                                  token,
                                                  secret)
                            .Users()
                            .GetFollowers()
                            .GetCursor(cursor.Value)
                            .AsJson();
                    var response = twitter.Request();
                    var followers = response.AsUsers();
                    cursor = response.AsNextCursor();
                    page++;
                    if (!cursor.HasValue ||
                        cursor.Value == 0 ||
                        page % PAGEINTERVAL == 0)
                    {
                        if (page % PAGEINTERVAL != 0)
                        {
                            finito = true;
                        }
                        Session["page"] = page;
                        moreTodo = false;
                    }
                    
                    // delete friends from follower
                    foreach (var user in followers)
                    {
                        if (!friendSet.Contains(user.Id))
                        {
                            var imgLink = "<img class='pi' align='absmiddle' src='" + user.ProfileImageUrl + "' />&nbsp;";
                            names.Add("<a href='http://twitter.com/" + user.ScreenName + "' target='_blank'>" + imgLink + user.ScreenName + "</a>");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Session["page"] = page;
                names.Add(ex.Message);
            }
            object[] data = new object[2];
            data[0] = names;
            data[1] = finito;
            return data;
        }

        public ActionResult GetList2(string screenName)
        {

            return Json(GetMeNoFollowResults(screenName, false));
        }

        public ActionResult MoreList2(string screenName)
        {

            return Json(GetMeNoFollowResults(screenName, true));
        }
    }
}
